import { watch, unref, ref } from 'vue'
import { getSelection, batchUpdateValue,fireExecute, sdp_language_workspace_extra_info } from '/src/utils/index'
import { post } from "/src/api/index";
import { ElMessage } from '/src/utils'
import { ElMessageBox } from 'element-plus'
import { exportWorkspace } from '/src/utils'
import { saveAs } from '/src/utils'
import { init as sdp_workspace_config } from '../sdp_workspace_config/custom'
import { init as sdp_project } from '../sdp_project/custom'
import { init as sdp_template } from '../sdp_template/custom'
import { init as sdp_sql } from '../sdp_sql/custom'

export function init(self) {
  [
    {
      prop: 'sdp_workspace_config',
      method: sdp_workspace_config,
    },
    {
      prop: 'sdp_project',
      method: sdp_project,
    },
    {
      prop: 'sdp_template',
      method: sdp_template,
    },
    {
      prop: 'sdp_sql',
      method: sdp_sql,
    },
  ].forEach( ele => {
    self[ele.prop] = unref({module: ref(ele.prop)})
    ele.method(self[ele.prop])
  })
  const module = self.module.value
  self.title = ref('workspace')
  self.extra_info_columns = sdp_language_workspace_extra_info.filter(ele => ele.label!='==')
  self.selection = false
  self.custom = {
    columns : [
      {
        prop: 'id',
        hide: true,
      },
      {
        prop: 'name',
        order: 'asc',
        width: 150,
      },
      {
        prop: 'db_host',
        width: 150,
      },
      {
        prop: 'db_port',
        width: 100,
      },
      {
        prop: 'db_database',
        width: 150,
      },
      {
        prop: 'db_username',
        width: 100,
      },
      {

      },
      {
        prop: 'db_jdbcurl',
        width: 300,
      },
      {

      },
      {
        prop: 'remark',
        width: 150,
      },
      {
        prop: 'db_password',
        hide: true,
      },
      {
        prop: 'extra_info',
        width: 100,
      },
      ...self.extra_info_columns.map(ele => {
        return {
          ...ele,
          prop: 'extra_info_'+ele.prop,
          width: 100,
        }
      }),
      {

      }
    ],

    editColumns : [
      {
        prop: 'id',
        hide: true,
      },
      {
        prop: 'name',
        required: true,
      },
      {
        prop: 'db_host',
        onchange: 'db_classname',
      },
      {
        prop: 'db_port',
        onchange: 'db_classname',
        empty_as_setnull: 1,
      },
      {
        prop: 'db_database',
        onchange: 'db_classname',
      },
      {

      },
      {
        prop: 'db_password',
        type: 'password',
      },
      {

      },
      {
        prop: 'db_jdbcurl',
        type: 'textarea'
      },
      {
        prop: 'db_classname',
        type: 'select',
        allowCreate: 1,
        list: [
          { label: 'Mysql', value: 'com.mysql.cj.jdbc.Driver' },
          { label: 'Mysql(旧版)', value: 'com.mysql.jdbc.Driver' },
          { label: 'H2', value: 'org.h2.Driver' },
          { label: 'postgresql', value: 'org.postgresql.Driver' },
        ].map(ele => ({label: ele.label + ' - ' + ele.value, value: ele.value})),
        onchange: param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage} = param
          if (form.db_classname && mode && mode.indexOf('init') < 0){
            if (form.db_classname == 'com.mysql.jdbc.Driver'
              || form.db_classname == 'com.mysql.cj.jdbc.Driver'
            ) {
              if (form.db_host && form.db_port && form.db_database) {
                form.db_jdbcurl = 'jdbc:mysql://' + form.db_host + ':' + form.db_port + '/' + form.db_database + '?useUnicode=true&characterEncoding=UTF8&serverTimezone=Asia/Shanghai&tcpKeepAlive=true&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true&tinyInt1isBit=false'
              }
            } else if (form.db_classname == 'org.h2.Driver') {
              if (form.db_database) {
                form.db_jdbcurl = 'jdbc:h2:' + form.db_database + ';AUTO_SERVER=TRUE;DB_CLOSE_DELAY=-1;MODE=MYSQL;DATABASE_TO_LOWER=TRUE'
              } else {
                form.db_jdbcurl = 'jdbc:h2:~/sdp;AUTO_SERVER=TRUE;DB_CLOSE_DELAY=-1;MODE=MYSQL;DATABASE_TO_LOWER=TRUE'
              }
            } else if (form.db_classname == 'org.postgresql.Driver') {
              if (form.db_host && form.db_port && form.db_database) {
                form.db_jdbcurl = 'jdbc:postgresql://' + form.db_host + ':' + form.db_port + '/' + form.db_database + '?useUnicode=true&characterEncoding=UTF8&serverTimezone=Asia/Shanghai&tcpKeepAlive=true&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true&tinyInt1isBit=false'
              }
            }
          }
        }
      },
      {
        prop: 'extra_info',
        type: 'textarea',
        rows: 5,
        onclick: param => {
          let txt = unref(unref(self).editDialogInfo).form.extra_info
          let target = param.srcElement
        },
      },
      ...self.extra_info_columns.map(ele => {
        let onchange = param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage} = param
          let extra_info
          if (form.extra_info) {
            try {
              extra_info = JSON.parse(form.extra_info)
            }catch(ex) {
              extra_info = {}
            }
          } else {
            extra_info = {}
          }
          let prop = column.prop.substring('extra_info_'.length)
          if (form[column.prop]) {
            extra_info[prop] = form[column.prop]
          } else {
            delete extra_info[prop]
          }
          form.extra_info = JSON.stringify(extra_info, null, 2)
          console.log('prop', prop, extra_info[prop])
          if(prop == 'is_local_ollama' && extra_info[prop]) {
            console.log('is_local_ollama')
            console.log('self.editColumns', self.editColumns)
            post('sdp_project', 'shell', {cmd:'ollama', param:'list'})
            .then( data => {
              console.log('data', data)
              if(data.result) {
                let c = self.editColumns.value.find(c => c.prop == 'extra_info_model')
                console.log('c', c)
                c.list = data.result.split('\n').filter((e,idx) => idx > 0).map((e,idx) => {
                  e = e.split(' ')[0].split('\t')[0].trim()
                  if(e) {
                    console.log('e', e)
                    return {label: e, value: e}
                  }
                }).filter(e => e)
                if(!c.list.length) {
                  ElMessage.error('ollama list无结果')
                }
              } else {
                ElMessage.error('ollama list无结果')
              }
            })
          }
        }
  
        if (ele.prop.indexOf('is_') >= 0) {
          return {
            ...ele,
            prop: 'extra_info_'+ele.prop,
            type: 'switch',
            onchange,
          }
        }
        return {
          ...ele,
          prop: 'extra_info_'+ele.prop,
          onchange,
        }
      }),
      {

      },
    ],

    queryColumns : [
      {
        prop: 'name_like',
        label: '名称',
        fixed: true,
        width: '200px',
      },
    ],

    remoteConfig : {
    },

    buttons: [
      {
        prop: 'import',
        label: '导入',
        loading: false,
        onclick: () => {
          unref(self.importDialogInfo).show({...self, dialogInfo: unref(self.importDialogInfo), query: unref(self.query)})
        }
      },
      {
        prop: 'buttonExport',
        label: '导出',
        loading: false,
        onclick: (param) => {
          let {editDialogInfo : dialogInfo, query, selectRows} = param
          if (!selectRows || selectRows.length == 0) {
            ElMessage.error(`请选择一条记录后再操作`);
            return;
          }
          let workspaceName = selectRows[0].name
          dialogInfo.loading = true
          exportWorkspace({...self, workspace_name: workspaceName})
            .then((datas) => {
              dialogInfo.loading = false
              let result = {}
              result[workspaceName] = datas

              result = JSON.stringify(result, null, 2)
              var file = new File([result], 'sdp_' + workspaceName + '.txt', {
                type: 'text/plain;charset=utf-8',
              })
              saveAs()(file)
            })
            .catch(ex => {
              dialogInfo.loading = false
              ElMessage.error(`无法导出，错误：${ex}`);
            })
        }
      },
    ],

    onMounted: () => {

    },

    onInit: () => {
      self.handleCurrentChange_ori = self.handleCurrentChange
      self.handleSearch_ori = self.handleSearch
      self.handleCurrentChange = (param) => {
        //必须判断param是否为空，否则会导致系统异常，例如删除工作区后，无法通过左侧菜单切换路由
        if (param) {
          unref(self.tableData).forEach( ele => {
            if (ele.id != param.id && ele.selected) {
              delete ele.selected
            }
          })
          self.handleCurrentChange_ori(param)
          param.selected = 1
        }
      }
      self.handleSearch = (param) => {
        return self.handleSearch_ori(param)
        .then(data => {
          unref(self.tableData).forEach( ele => {
            if (ele.extra_info) {
              let j = JSON.parse(ele.extra_info)
              for(let p in j) {
                ele['extra_info_'+p] = j[p]
              }
              ele.extra_info = JSON.stringify(j, null, 2)
            }
          })
        })
      }
      self.handleDelete = (index) => {
        if (self.selectRows.value.length == 0) {
          ElMessage.error('请先选择记录');
          return;
        }
        let workspace_name = unref(self.selectRows)[0].name
        if (!workspace_name) {
          ElMessage.error('逻辑错误：无法获取workspace_name');
          return;
        }
          // 二次确认删除
          ElMessageBox.confirm("确定要删除吗？", "提示", {
              type: "warning",
          })
              .then(() => {
                self.loadingDelete.value = true;
                self.discardCount.value = false
                post('sdp_sql', 'list', {workspace_name})
                .then( data => {
                  if (data && data.length > 0) {
                    return post('sdp_sql', 'delete', {id:data.map(item => item.id)})
                  }
                  return 0
                })
                .then( data => {
                  if ( data >= 0) {
                    return post('sdp_template', 'list', {workspace_name})
                  }
                  return []
                })
                .then( data => {
                  if (data && data.length > 0) {
                    return post('sdp_template', 'delete', {id:data.map(item => item.id)})
                  }
                  return 0
                })
                .then( data => {
                  if ( data >= 0) {
                    return post('sdp_project', 'list', {workspace_name})
                  }
                  return []
                })
                .then( data => {
                  if (data && data.length > 0) {
                    return post('sdp_project', 'delete', {id:data.map(item => item.id)})
                  }
                  return 0
                })
                .then( data => {
                  if ( data >= 0) {
                    return post('sdp_workspace_config', 'list', {workspace_name})
                  }
                  return []
                })
                .then( data => {
                  if (data && data.length > 0) {
                    return post('sdp_workspace_config', 'delete', {id:data.map(item => item.id)})
                  }
                  return 0
                })
                .then( data => {
                  if ( data >= 0) {
                    return post('sdp_workspace', 'list', {name: workspace_name})
                  }
                  return []
                })
                .then( data => {
                  if (data && data.length > 0) {
                    return post('sdp_workspace', 'delete', {id:data.map(item => item.id)})
                  }
                  return 0
                })
                .then( data => {
                  if ( data >= 0) {
                    ElMessage.success(`成功`);
                    self.handleSearch({forceCount:true})
                    return;
                  }
                  ElMessage.error(`失败:${data}`);
                })
                .catch(err => {
                  ElMessage.error(`失败:${err}`, err);
                })
                .finally (()=> {
                  self.loadingDelete.value = false;
                })
              })
              .catch(err => {
                ElMessage.error(`失败:${err}`, err);
                self.loadingDelete.value = false;
              });
      }
      unref(self.editDialogInfo).buttons = [
        {
          prop: 'testConnect',
          label: '测试连接',
          loading: false,
          onclick: (param) => {
            const { button } = param
            let dialogInfo = unref(self.editDialogInfo)
            let form = self.getFormAndcheckRequired(dialogInfo)
            if (!form) {
              return;
            }
            if (form.db_password == '******') {
              delete form.db_password
            }

            button.loading = true
            post('sdp_workspace', 'test_connect', form)
            .then( data => {
              if (data >= 0) {
                ElMessage.success(`成功`);
                button.loading = false
              } else {
                ElMessage.error(`失败:${data}`);
                button.loading = false
              }
            })
            .catch(err => {
              ElMessage.error(`失败:${err}`, err);
              button.loading = false
            })
          }
        },
      ]
    },

  }
}

